package com.speech.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class StringHasher
{
	private static final long FNV_64_INIT = 0xcbf29ce484222325L;
    private static final long FNV_64_PRIME = 0x100000001b3L;
    
    private static final long FNV_32_INIT = 2166136261L;
    private static final int FNV_32_PRIME = 16777619;
    
    //即使 GetHashId4Url 和 GetFNV64Hash 一模一样，也要分开这个函数出来
    //防止以后 GetHashId4Url 有变化
    public static long GetHashId4Url(String str)
    {
    	return GetFNV64Hash(str);
    }
    
    //删除最高位防止负数
    public static long GetFNV64Hash(String str) {
    	long rv = FNV_64_INIT;
        int len = str.length();
        for (int i = 0; i < len; i++) {
                rv *= FNV_64_PRIME;
                rv ^= str.charAt(i);
        }
        return rv & 0x7FFFFFFFFFFFFFFFL;
    }
    
    //删除最高位防止负数
    public static int GetFNV32Hash(String str) {
    	long rv = FNV_32_INIT;
		int len = str.length();
		for (int i = 0; i < len; i++) {
		        rv *= FNV_32_PRIME;
		        rv ^= str.charAt(i);
		}
		return (int) (rv & 0x7FFFFFFF);
    }
    
    //删除最高位防止负数
    public static long GetFNV64HashFromFile(String str_file) {
    	long rv = FNV_64_INIT;
    	try {
    		FileInputStream fis = new FileInputStream(str_file);
			int ch;
			while((ch = fis.read()) != -1) {
				rv *= FNV_32_PRIME;
		        rv ^= ch;
			}
			fis.close();
		} catch (Exception e) {
			rv = 0;
		}
    	
    	return rv & 0x7FFFFFFFFFFFFFFFL;
    }
    
    public static long GetFNV64HashFromBuffer(ByteArrayOutputStream bstream) {
    	long rv = FNV_64_INIT;
    	byte [] buff = bstream.toByteArray();
    	for(int i=0; i<buff.length; i++) {
			rv *= FNV_32_PRIME;
	        rv ^= buff[i];
    	}
    	return rv & 0x7FFFFFFFFFFFFFFFL;
    }
}
